﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastData;
using System.Threading;

namespace FastCtr
{
    public partial class NewSQL : UserControl
    {
        public enum ConnectType
        {
            MySql,
            SqlServer
        }        
        public ISqlClient SqlClient;
        DateTime timeoutsign = DateTime.Now - new TimeSpan(0, 0, 5);
        public Setting setting;
        private string _SaveName;
        public ConnectType connectType;
        public bool State = false;
        public TimeSpan DelayTime;
        public string SaveName
        {
            get
            {
                return _SaveName;
            }
            set
            {
                _SaveName = value;
            }
        }

        public NewSQL()
        {            
            InitializeComponent();
        }

        public NewSQL(string _savename= "newSQL")
        {
            _SaveName = _savename;
            InitializeComponent();
            ReadSQLConfig();
        }

        private void NewSQL_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(new object[] { ConnectType.MySql.ToString(), ConnectType.SqlServer.ToString() });
            textBox1.Text = setting.ip;
            textBox2.Text = setting.user;
            textBox3.Text = setting.password;
            textBox4.Text = setting.database;
            checkBox2.Checked = setting.isLast;
            textBox6.Text = setting.lastCount.ToString();
            comboBox1.SelectedIndex = comboBox1.Items.IndexOf(connectType.ToString());
        }

        //读取SQL配置
        public void ReadSQLConfig()
        {
            Name = _SaveName;
            ParentChanged += new EventHandler(newUserControl_ParentChanged);
            try
            {
                setting = new Setting();
                setting = (Setting)FastData.SaveStatic.ReadBinF(_SaveName);
                connectType = (ConnectType)SaveStatic.ReadBinF(_SaveName + ".SqlType");
                if (connectType == ConnectType.MySql)
                {
                    SqlClient = new MySQL();
                }
                else
                {
                    SqlClient = new SqlServer();
                }
                SqlClient.database = setting.database;
                SqlClient.datasource = setting.ip;
                SqlClient.userid = setting.user;
                SqlClient.password = setting.password;
            }
            catch (Exception exp)
            {
                connectType = ConnectType.MySql;
                setting.database = "";
                setting.ip = "0.0.0.0";
                setting.password = "";
                setting.user = "";
                setting.isLast = true;
                setting.lastCount = 10000;
                MessageBox.Show("您可能需要配置数据库连接参数！" + exp);
            }
        }

        public void Connect()
        {
             SqlClient.SqlConn();

        }



        public void StartKeepOnline()
        {
            Task taskState = new Task(() =>
            {
                while (true)
                {
                    Thread.Sleep(100);
                    DelayTime = DateTime.Now - timeoutsign;
                    if (DelayTime >= new TimeSpan(0, 0, 0, 5))
                    {
                        State = false;
                    }
                    else
                    {
                        State = true;
                    }
                }
            }, TaskCreationOptions.LongRunning);
            taskState.Start();

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        if (SqlClient.SqlConnTest())
                        {
                            timeoutsign = DateTime.Now;
                        }
                    }
                    catch
                    {
                    }
                    Thread.Sleep(2000);
                }
            }, TaskCreationOptions.LongRunning);
        }

        public void DisConnect()
        {
            SqlClient.SqlClose();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                connectType = (ConnectType)Enum.Parse(typeof(ConnectType), comboBox1.Text);
                setting.ip = textBox1.Text;
                setting.user = textBox2.Text;
                setting.password = textBox3.Text;
                setting.database = textBox4.Text;
                setting.isLast = checkBox2.Checked;
                setting.lastCount = int.Parse(textBox6.Text);
                if (connectType == ConnectType.MySql)
                {
                    SqlClient = new MySQL();
                }
                else
                {
                    SqlClient = new SqlServer();
                }
                SqlClient.database = setting.database;
                SqlClient.datasource = setting.ip;
                SqlClient.userid = setting.user;
                SqlClient.password = setting.password;
                setting.ConnStr = SqlClient.ConnStr;
            }
            catch
            {
                MessageBox.Show("输入信息格式有误，请检查！");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FastData.SaveStatic.SaveBinF(_SaveName, setting);
            FastData.SaveStatic.SaveBinF(_SaveName + ".SqlType", (ConnectType)Enum.Parse(typeof(ConnectType), comboBox1.Text));
        }

        [Serializable]
        public struct Setting
        {
            public string ConnStr { get; set; }
            public string ip { get; set; }
            public string user { get; set; }
            public string password { get; set; }
            public string database { get; set; }
            public bool isLast { get; set; }
            public int lastCount { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Connect();
            }
            catch (Exception exp)
            {
                MessageBox.Show("数据库打开异常！" + exp);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            GC.Collect();
            label12.Text = DelayTime.TotalMilliseconds.ToString() + " ms";

            if (SqlClient == null)
            {
                return;
            }
            if (SqlClient.IsConnected)
            {
                label7.BackColor = Color.LimeGreen;
                groupBox1.Enabled = false;
                button1.Enabled = false;
                button4.Enabled = false;
                button3.Enabled = false;
                button2.Enabled = true;
            }
            else
            {
                label7.BackColor = Color.Red;
                groupBox1.Enabled = true;
                button1.Enabled = true;
                button4.Enabled = true;
                button3.Enabled = true;
                button2.Enabled = false;
            }
        }
        
        private void newUserControl_ParentChanged(object sender, EventArgs e)
        {
            if (Parent != null)
            {
                if (ParentForm != null)
                {
                    ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
                    ParentForm.AutoSize = true;
                    ParentForm.Text = Name;
                    //Dock = DockStyle.Fill;
                    ParentForm.Width = 1000;
                    ParentForm.Height = 500;
                }
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }
        }

        private void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Parent.Controls.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SqlClient.SqlClose();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Parent == null)
                return;
            checkBox1.Checked = false;
            DataSet dataSet = SqlClient.FindLastLines(comboBox2.Text, setting.lastCount);
            dgvDataDisp.DataPageSource = dataSet.Tables[0].ConverIntoDataPage(10);
            //dgvDataDisp.AutoResizeColumns();
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            DateTime dt1 = DateTime.Now;
            if (Parent == null)
                return;
            if (checkBox1.Checked)
            {
                DataSet dataSet = SqlClient.FindAllLike(comboBox2.Text, setting.lastCount, comboBox3.Text, textBox5.Text);
                DateTime dt2 = DateTime.Now;
                TimeSpan span = dt2 - dt1;
                label9.Text = "耗时：" + span.TotalMilliseconds.ToString() + " ms";
                dgvDataDisp.DataPageSource = dataSet.Tables[0].ConverIntoDataPage(10);
                //dgvDataDisp.AutoResizeColumns();
            }
        }

        private void checkBox1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                comboBox3.Items.Clear();
                List<string> list = SqlClient.FindAllTableColums(comboBox2.Text);
                comboBox3.Items.AddRange(list.ToArray());
                comboBox3.SelectedIndex = 0;
            }
            else
            {
                checkBox1.Checked = false;
                DataSet dataSet = SqlClient.FindLastLines(comboBox2.Text, setting.lastCount);
                dgvDataDisp.DataPageSource = dataSet.Tables[0].ConverIntoDataPage(10);
                //dgvDataDisp.AutoResizeColumns();
            }
        }

        private void comboBox2_DropDown(object sender, EventArgs e)
        {
            List<string> list = SqlClient.FindAllTables();
            comboBox2.Items.Clear();
            comboBox2.Items.AddRange(list.ToArray());
        }
    }





   
}

